<!--
 * @Author: lijilong
 * @Date: 2024-06-15
-->
<template>
    <view class="select-wrap">
        <view class="input" :class="[!value ? 'placeholder' : '', border ? 'border' : '']"
            :style="'justify-content:' + align" @click="showDialog">
            <text>{{ formatValue || placeholder }}</text>
            <text>
                <text class="arrow" v-show="formatValue" style="margin-right:10rpx">
                    <wd-icon name="close-circle-filled" size="15px" @click.stop="clearValue"></wd-icon>
                </text>
                <text class="arrow cuIcon-right"></text>

            </text>

        </view>
        <block v-if="show">
            <view class="mask" :class="visible ? 'on' : ''" @click="visible = false; show = false"></view>
            <view class="picker-wrap" :class="visible ? 'on' : ''">
                <view class="header">
                    <view class="cancel text-gray" @click="visible = false; show = false">取消</view>
                    <view>{{ placeholder }}</view>
                    <view class="ok text-blue" @click="done">确定</view>
                </view>
                <picker-view :indicator-style="indicatorStyle" :value="dateTime" @change="change" :immediate-change="true"
                    class="picker-view">
                    <picker-view-column v-if="formats.includes('YYYY')" style="padding-left: 10rpx">
                        <view class="item" v-for="(item, index) in years" :key="index">
                            {{ item }}
                            <text>年</text>
                        </view>
                    </picker-view-column>
                    <picker-view-column v-if="formats.includes('MM')">
                        <view class="item" v-for="(item, index) in months" :key="index">
                            {{ item }}
                            <text>月</text>
                        </view>
                    </picker-view-column>
                    <picker-view-column v-if="formats.includes('DD')">
                        <view class="item" v-for="(item, index) in days" :key="index">
                            {{ item }}
                            <text>日</text>
                        </view>
                    </picker-view-column>
                    <picker-view-column v-if="formats.includes('HH')">
                        <view class="item" v-for="(item, index) in hours" :key="index">
                            {{ item }}
                            <text>时</text>
                        </view>
                    </picker-view-column>
                    <picker-view-column v-if="formats.includes('mm')">
                        <view class="item" v-for="(item, index) in minutes" :key="index">
                            {{ item }}
                            <text>分</text>
                        </view>
                    </picker-view-column>
                    <picker-view-column v-if="formats.includes('ss')">
                        <view class="item" v-for="(item, index) in seconds" :key="index">
                            {{ item }}
                            <text>秒</text>
                        </view>
                    </picker-view-column>
                </picker-view>
            </view>
        </block>
    </view>
</template>
  
<script>
import dayjs from 'dayjs';

export default {
    name: 'datePicker',
    props: {
        valueFormat: {
            type: String,
            default: 'YYYY-MM-DD HH:mm:ss',
        },
        labelFormat: {
            type: String,
        },
        defaultDate: {
            type: [Boolean, String],
            default: false,
        },
        placeholder: {
            type: String,
            default: '请选择时间',
        },
        value: {
            type: String,
        },
        limit: {
            type: Object,
        },
        align: {
            type: String,
            default: 'space-between',
        },
        border: {
            type: [Boolean, String],
            default: false,
        },
        disabled: {
            type: [Boolean, String],
            default: false,
        },
    },
    data() {
        const years = [];
        const months = [];
        const days = [];
        const hours = [];
        const minutes = [];
        const seconds = [];
        for (
            let i = dayjs().subtract(1, 'year').format('YYYY');
            i <= dayjs().add(10, 'year').format('YYYY');
            i++
        ) {
            years.push(String(i));
        }

        for (let i = 1; i <= 12; i++) {
            months.push(i < 10 ? `0${i}` : `${i}`);
        }

        for (let i = 1; i <= 31; i++) {
            days.push(i < 10 ? `0${i}` : `${i}`);
        }

        for (let i = 0; i <= 23; i++) {
            hours.push(i < 10 ? `0${i}` : `${i}`);
        }

        for (let i = 0; i <= 59; i++) {
            minutes.push(i < 10 ? `0${i}` : `${i}`);
            seconds.push(i < 10 ? `0${i}` : `${i}`);
        }
        return {
            picker: [],
            tempDate: '',
            years,
            year: null,
            months,
            month: null,
            days,
            day: null,
            hours,
            hour: null,
            minutes,
            minite: null,
            seconds,
            second: null,
            show: false,
            visible: false,
            indicatorStyle: `height: 50px;`,
            dateTime: [],
        };
    },
    computed: {
        format() {
            return this.labelFormat || this.valueFormat
        },
        formats() {
            return this.valueFormat.split(/:|\s|-/);
        },
        formatValue() {
            if (!this.value) return ''
            return dayjs(this.value).format(this.format)
        }
    },
    methods: {
        updateTime() {
            const date = new Date();
            this.year = String(date.getFullYear());
            this.month = date.getMonth() + 1;
            this.day = date.getDate();
            this.hour = date.getHours();
            this.minite = date.getMinutes();
            this.second = date.getSeconds();
        },
        initDate() {
            this.updateTime();
            let arr = [];
            // if (this.value) {
            //     const T = this.value.split(/:|\s|-/);
            //     this.formats.forEach((f, i) => {
            //         switch (f) {
            //             case 'YYYY':
            //                 arr.push(this.years.indexOf(T[i]));
            //                 break;
            //             case 'MM':
            //                 arr.push(this.months.indexOf(T[i]));
            //                 break;
            //             case 'DD':
            //                 arr.push(this.days.indexOf(T[i]));
            //                 break;
            //             case 'HH':
            //                 arr.push(this.hours.indexOf(T[i]));
            //                 break;
            //             case 'mm':
            //                 arr.push(this.minutes.indexOf(T[i]));
            //                 break;
            //             case 'ss':
            //                 arr.push(this.seconds.indexOf(T[i]));
            //                 break;
            //             default:
            //         }
            //     });
            // } else {

            // }
            this.formats.forEach((f, i) => {
                switch (f) {
                    case 'YYYY':
                        arr.push(this.years.indexOf(this.year));
                        break;
                    case 'MM':
                        arr.push(this.month - 1);
                        break;
                    case 'DD':
                        arr.push(this.day - 1);
                        break;
                    case 'HH':
                        arr.push(this.hour);
                        break;
                    case 'mm':
                        arr.push(this.minite);
                        break;
                    case 'ss':
                        arr.push(this.second);
                        break;
                    default:
                }
            });
            this.dateTime = arr;
            console.log(this.dateTime)
            if (this.defaultDate) {
                !this.value && this.updateDateTimeValue(arr);
            }

        },
        showDialog() {
            this.show = true;
            this.$nextTick(() => {
                this.visible = true;
                this.initDate()
            });
        },
        clearValue() {
            this.$emit('update:value', '');
        },
        change(e) {
            const v = e.detail.value;
            this.dateTime = v;
        },
        getDays(y, m) {
            let days;
            const dayArr = [];
            // 当份为二，根据闰年还是非闰年判断天数
            if (m === 2) {
                days = y % 4 === 0 ? 29 : 28;
            } else if (m === 1 || m === 3 || m === 5 || m === 7 || m === 8 || m === 10 || m === 12) {
                // 份为：1,3,5,7,8,10,12 ，为大.则天数为31；
                days = 31;
            } else {
                // 其他份，天数为：30.
                days = 30;
            }
            for (let i = 1; i <= days; i++) {
                if (i < 10) {
                    dayArr.push(`0${i}`);
                } else {
                    dayArr.push(`${i}`);
                }
            }
            // 输出天数
            return dayArr;
        },
        getDateByPicker(v) {
            const temp = [];
            this.formats.forEach((f, i) => {
                switch (f) {
                    case 'YYYY':
                        temp.push(this.years[v[i]], '-');
                        break;
                    case 'MM':
                        temp.push(this.months[v[i]], '-');
                        break;
                    case 'DD':
                        temp.push(this.days[v[i]], ' ');
                        break;
                    case 'HH':
                        temp.push(this.hours[v[i]], ':');
                        break;
                    case 'mm':
                        temp.push(this.minutes[v[i]], ':');
                        break;
                    case 'ss':
                        temp.push(this.seconds[v[i]], ':');
                        break;
                    default:
                }
            });
            this.tempDate = temp.join('').replace(/(^\s*)|((:|\s*)$)/g, '');
        },
        updateDateTimeValue(dateTime) {
            const time = dateTime || this.dateTime;
            this.getDateByPicker(time);
            if (this.limit) {
                if (this.$date(this.tempDate).valueOf() <= this.$date(this.limit.value).valueOf()) {
                    uni.showToast({
                        title: this.limit.tip,
                        icon: 'none',
                    });
                    return;
                }
            }
            this.$emit('update:value', this.tempDate);
            this.$emit('change', this.tempDate);
        },
        done() {
            this.updateDateTimeValue(this.dateTime);

            this.visible = false;
        },
    },
    // created() {
    //   this.initDate();
    // },
};
</script>
  
<style lang="scss" scoped>
.select-wrap {
    flex: 1;

    .placeholder {
        color: #bfbfbf;
        font-size: 28rpx;
    }

    .input {
        display: flex;
        align-items: center;
        height: 60rpx;
        line-height: 60rpx;
        border-radius: 8rpx;
        white-space: no-wrap;
        overflow: hidden;
        text-overflow: ellipsis;

        &.border {
            border: 1rpx solid #dcdfe6;
        }
    }

    .arrow {
        font-size: 28rpx;
        color: #dcdfe6;
        font-size: 30rpx;
        width: 60rpx;
        text-align: center;
    }
}

.mask {
    position: fixed;
    width: 100vw;
    height: 100vh;
    bottom: 0;
    left: 0;
    visibility: hidden;
    z-index: 999998;
    background: rgba(0, 0, 0, 0);
    transition: all 0.3s;

    &.on {
        background: rgba(0, 0, 0, 0.5);
        visibility: visible;
    }
}

.picker-wrap {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 999999;
    width: 100vw;
    border-top-right-radius: 5rpx;
    border-top-left-radius: 5rpx;
    overflow: hidden;
    transform: translateY(100%);
    transition: all 0.15s ease-in-out;

    &.on {
        transform: translateY(0);
    }

    .header {
        display: flex;
        justify-content: space-between;
        height: 100rpx;
        background: #fff;
        line-height: 100rpx;
        padding: 0 30rpx;
        font-size: 30rpx;
        border-bottom: 1rpx solid #f1f1f1;
    }

    .picker-view {
        width: 100vw;
        height: 600rpx;
        background-color: #fff;
        font-size: 38rpx;
    }

    .item {
        height: 50px;
        line-height: 50px;
        align-items: center;
        justify-content: center;
        text-align: center;

        text {
            font-size: 26rpx;
            margin-left: 5rpx;
            color: #333;
        }
    }
}
</style>
  